// 自制阻塞
export const sleep = (min = 1000, max?: number) => {
  const time = randomNum(min, max)
  return new Promise((resolve) => setTimeout(resolve, time))
}

// 范围随机数(必须用function)
export const randomNum = (a: number, b?: number) => {
  if (!b) {
    const max = a
    return Math.random() * max
  } else {
    const min = a
    const max = b
    return Math.random() * (max - min) + min
  }
}

// url补充协议
export const getProtocolUrl = (url: string) => {
  if (url.indexOf('://') !== -1) {
    return url
  } else {
    const result = window.location.protocol + '//' + url
    return result.replace('////', '//')
  }
}

// 富文本去标签
export const removeTAG = (str: string) => {
  return str.replace(/<[^>]+>/g, '')
}

// 控制频率
let lock = false // 公共锁
let timer: NodeJS.Timeout | undefined = undefined
export const frequency = (fn: () => unknown, ms = 60) => {
  clearTimeout(timer)
  if (!lock) {
    fn()
    lock = true
    setTimeout(() => (lock = false), ms)
  } else {
    timer = setTimeout(fn, ms / 2)
  }
}

export default {
  sleep,
  randomNum,
  getProtocolUrl,
  removeTAG,
  frequency
}
